package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/updateUserStatus")
public class UpdateUserStatusServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 检查管理员权限
        HttpSession session = request.getSession();
        if (session.getAttribute("adminRole") == null || (int)session.getAttribute("adminRole") != 2) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "无权限执行此操作");
            out.write(gson.toJson(result));
            out.flush();
            return;
        }
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取请求参数
            String userId = request.getParameter("userId");
            String statusStr = request.getParameter("status");
            
            // 打印所有请求参数，帮助调试
            System.out.println("UpdateUserStatusServlet - 所有请求参数:");
            Map<String, String[]> paramMap = request.getParameterMap();
            for (String key : paramMap.keySet()) {
                String[] values = paramMap.get(key);
                System.out.println(key + ": " + (values.length > 0 ? values[0] : "null"));
            }
            
            // 记录日志，帮助调试
            System.out.println("UpdateUserStatusServlet - 更新用户状态: userId=" + userId + ", status=" + statusStr);
            
            if (userId == null || userId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                out.write(gson.toJson(result));
                return;
            }
            
            if (statusStr == null || statusStr.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "状态值不能为空");
                out.write(gson.toJson(result));
                return;
            }
            
            int status;
            try {
                status = Integer.parseInt(statusStr);
            } catch (NumberFormatException e) {
                result.put("success", false);
                result.put("message", "无效的状态值: " + statusStr);
                out.write(gson.toJson(result));
                return;
            }
            
            if (status != 0 && status != 1) {
                result.put("success", false);
                result.put("message", "无效的状态值: " + status + "，只能是0(禁用)或1(正常)");
                out.write(gson.toJson(result));
                return;
            }
            
            boolean success = userService.updateUserStatus(userId, status);
            
            if (success) {
                String statusMessage;
                switch (status) {
                    case 0:
                        statusMessage = "用户已被禁用";
                        break;
                    case 1:
                        statusMessage = "用户已恢复使用权限";
                        break;
                    default:
                        statusMessage = "用户状态已更新";
                }
                result.put("success", true);
                result.put("message", statusMessage);
            } else {
                result.put("success", false);
                result.put("message", "更新用户状态失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "更新用户状态失败：" + e.getMessage());
        }
        
        // 打印最终返回的JSON
        String jsonResult = gson.toJson(result);
        System.out.println("UpdateUserStatusServlet - 返回JSON: " + jsonResult);
        
        out.write(jsonResult);
        out.flush();
    }
} 